package com.moleq.mginventory.activities;

import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.OnResultListener;
import com.moleq.db.DatabaseHelper;
import com.moleq.device.BaseScanner;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.IDeviceEvent;
import com.moleq.device.ScannerSetting;
import com.moleq.dialog.DateSettingSelectionDialog;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.logic.UPC;
import com.moleq.mgpos.activities.R;
import com.moleq.models.ItemReceive;
import com.moleq.models.ItemSetting;

import com.moleq.service.ItemPicService;
import com.moleq.service.ItemReceiveService;
import com.moleq.service.ItemSettingService;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;

public class MGInventoryActivity extends MoleQBaseActivity {

//	private Intent mServiceIntent;
	public DatabaseHelper dbHelper,posdbHelper;
	private Context sharedContext = null;
	public ItemSettingService mItemSettingService;
	public ItemReceiveService mInventoryService;
	public EditText et_upc,et_date;
	private Button btn_search,btn_save;
	private TextView tv_upc;
	private TextView tv_name;
	private TextView tv_description;
	private TextView tv_NetWT;
	public boolean isNormalize = false;
	private EditText et_case;
	private EditText et_cost;
	private EditText et_qty,et_total_qty;
	private Button btn_exit;
	private Context sharedIntyContext = null;
	private int total_case,qty;
	private String ls_search,date;
	private double cost;
	private DateSettingSelectionDialog mDateSettingSelectionDialog;
	private DeviceSettingService mSettingService;
	private DeviceManager mDeviceManager;
	private ItemPicService mItemPicService;
	private ImageView iv_photo;
	private LinearLayout ll_layout;
	private EditText et_unit_cost;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// Hidden title
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_mginventory);

//		mServiceIntent = new Intent(this, InventoryService.class);
//		startService(mServiceIntent);
		
		 try {
				sharedContext = this.createPackageContext("com.moleq.posdb",Context.CONTEXT_IGNORE_SECURITY);
				if (sharedContext == null) {
					return;
				}
			} catch (Exception e) {
				String error = e.getMessage();
				return;
			}
	        
		 try {
				sharedIntyContext  = this.createPackageContext("com.moleq.inventory.db",Context.CONTEXT_IGNORE_SECURITY);
				if (sharedIntyContext == null) {
					return;
				}
			} catch (Exception e) {
				return;
			}
		 
		 
	        mItemSettingService = new ItemSettingService(sharedContext);
	        mInventoryService = new ItemReceiveService(sharedIntyContext);
	        
	        et_upc = (EditText)findViewById(R.id.et_upc);
	        et_case = (EditText)findViewById(R.id.et_case);
	        et_cost = (EditText)findViewById(R.id.et_cost);
	        et_qty = (EditText)findViewById(R.id.et_qty);
	        et_date = (EditText)findViewById(R.id.et_date);
	        iv_photo = (ImageView)findViewById(R.id.iv_photo);
	        ll_layout = (LinearLayout)findViewById(R.id.ll_layout);
	        
	        btn_search = (Button)findViewById(R.id.btn_search);
	        btn_search.setOnClickListener(onClickListener);
	        btn_exit = (Button)findViewById(R.id.btn_exit);
	        btn_exit.setOnClickListener(onClickListener);
	        btn_save = (Button)findViewById(R.id.btn_save);
	        btn_save.setOnClickListener(onClickListener);
	        et_date.setOnClickListener(onClickListener);
	        ll_layout.setOnClickListener(onClickListener);
	        
	        
	        tv_upc = (TextView)findViewById(R.id.tv_upc);
	        tv_name = (TextView)findViewById(R.id.tv_name);
	        tv_description = (TextView)findViewById(R.id.tv_description);
	        tv_NetWT = (TextView)findViewById(R.id.tv_NetWT);
	        et_total_qty = (EditText)findViewById(R.id.et_total_qty);
	        et_unit_cost = (EditText)findViewById(R.id.et_unit_cost);
	        
	        et_case.addTextChangedListener(watcher);
			et_cost.addTextChangedListener(watcher);
			et_qty.addTextChangedListener(watcher);
//			et_date.addTextChangedListener(watcher);
			  
	        SetEnabledTrue();
	        et_date.setText(MoleQUtil.getNowwithFormat("yyyy-MM-dd"));
	        mDateSettingSelectionDialog = new DateSettingSelectionDialog(this);
	        
	     // =========== setup scanner =================
			mDeviceManager = DeviceManager.getInstance();
			mSettingService = new DeviceSettingService(sharedContext);
			mItemPicService = new ItemPicService(sharedContext);
			
			List<ScannerSetting> scannerSettings = mSettingService
					.getScannerSettings();

			// check scanner
			int iScannerCount = scannerSettings.size();
			for (int i = 0; i < iScannerCount; i++) {
				int iPort = scannerSettings.get(i).getPort();
				for (int j = i + 1; j < iScannerCount; j++) {
					if (iPort == scannerSettings.get(j).getPort()) {
						// Toast.makeText(PriceSettingActivity.this,
						// " Scanner setup error. Please check.",
						// Toast.LENGTH_LONG).show();
						MessageBox.show(this, " Scanner setup error. Please check.");
						finish();
					}

				}
			}

			for (int i = 0; i < scannerSettings.size(); i++) {
				BaseScanner baseScanner = new BaseScanner();
				baseScanner.setScannerSetting(scannerSettings.get(i));
				mDeviceManager.addScanner(baseScanner);
			}

			// open scanner
			for (int i = 0; i < mDeviceManager.scanners.size(); i++) {
				mDeviceManager.scanners.get(i).onConnect();
				mDeviceManager.scanners.get(i).setCallbackEvent(this);
				mDeviceManager.scanners.get(i).onEnableScanner();
			}

			// ============================================

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		getMenuInflater().inflate(R.menu.activity_mgstock, menu);
		return true;
	}
	
	 public OnClickListener onClickListener = new OnClickListener() {

			public void onClick(View view) {
				switch (view.getId()) {
				case R.id.btn_search:
					search();
					break;
				case R.id.btn_exit:
					MessageBox.show(MGInventoryActivity.this,MGInventoryActivity.this.getResources().
							getString(R.string.msg_exit_program).toString(), onClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
					break;
					
				case R.id.btn_save:
					
					if (!validation()) return;
					
					total_case =  Integer.valueOf(et_case.getText().toString().trim().equals("")?"0":et_case.getText().toString());
					cost = Double.valueOf(et_cost.getText().toString().trim().equals("")?"0":et_cost.getText().toString());
					qty =Integer.valueOf(et_qty.getText().toString().trim().equals("")?"0":et_qty.getText().toString());;
					date = MoleQUtil.fixDateTime(et_date.getText().toString());
					
					if(mInventoryService.insertInventory(new ItemReceive(tv_upc.getText().toString(),null,total_case,qty,cost,date))){
						
						Toast.makeText(MGInventoryActivity.this, "Save completed.",Toast.LENGTH_SHORT).show();
						clearText();
					}
					
					break;
				case R.id.et_date:
					mDateSettingSelectionDialog.show(R.id.et_date, et_date.getText().toString());
					break;
				case R.id.ll_layout:
					Keyboard();
					break;
				}
			}
	    };
	    
	    public void dispose() {
			// disable all scanner
			mDeviceManager.disposeScanner();

			// disabel scale
			mDeviceManager.disposeScale();

			if (mDeviceManager.screen != null && mDeviceManager.screen.isConnected()) {
				mDeviceManager.screen.onDisconnect();
			}

			mDeviceManager.resetALLDevices();
				
		}
	    
	    public void search(){
	    	
	    	ls_search = et_upc.getText().toString();
			UPC upc = new UPC(ls_search, UPC.INPUT_BY_MANUAL,isNormalize);
			String code = upc.code;
			if (!code.equals("")) {
				ItemSetting item = mItemSettingService.findByUpc(code);
				if (item != null) {
					tv_upc.setText(item.getUpc());
					tv_name.setText(item.getName());
					tv_NetWT.setText(item.getNetWtText());
					tv_description.setText(item.getDesc());
					Bitmap bp = mItemPicService.getImageByUPC(code);
					if (bp == null) {
						Bitmap logo = BitmapFactory.decodeResource(MGInventoryActivity.this
								.getApplicationContext().getResources(),
								R.drawable.moleqlogo);
						iv_photo.setImageBitmap(logo);
					} else {
						iv_photo.setImageBitmap(bp);
					}
					et_upc.setText("");
					et_case.setFocusable(true);
			    	et_case.requestFocus();
				}else{
					MessageBox.show(MGInventoryActivity.this,"Item Not Found");
					return;
				}
			}
	    }
	    public boolean validation(){
	    	
			if (tv_upc.getText().toString().trim().equals("")) {
			
				MessageBox.show(this, "Please search the item.");
				return false;
			}

//	    	if (et_case.getText().toString().trim().equals("")) {
//	    		
//	    		MessageBox.show(this, "# of Case can not be empty.");
//	    		return false;
//			}
//			if (et_cost.getText().toString().trim().equals("")) {
//				    		
//	    		MessageBox.show(this, "Qty of Case can not be empty.");
//	    		return false;
//			}
//			if (et_qty.getText().toString().trim().equals("")) {
//				
//				MessageBox.show(this, "Cost per Case can not be empty.");
//				return false;
//			}
			
			if (et_date.getText().toString().trim().equals("")) {
				
				MessageBox.show(this, "Date can not be empty.");
				return false;
			}
	    	
	    	return true;
	    	
	    }
	    public void SetEnabledTrue() {
	    	//////////
		}
	    
	    public void SetEnabledFalse() {
	    	//////////
		}
	    
	    public void clearText(){
	    	 et_case.setText("");
			 et_cost.setText("");
			 et_qty.setText("");
			 et_date.setText(MoleQUtil.getNowwithFormat("yyyy-MM-dd"));
			 tv_description.setText("");
			 tv_name.setText("");
			 tv_NetWT.setText("");
			 tv_upc.setText("");
			 et_unit_cost.setText("");
			 et_total_qty.setText("");
			 et_upc.setFocusable(true);
			 et_upc.requestFocus();
			 Bitmap logo = BitmapFactory.decodeResource(MGInventoryActivity.this
						.getApplicationContext().getResources(),
						R.drawable.moleqlogo);
			 iv_photo.setImageBitmap(logo);
	    }
	    
	    public void Keyboard() {
			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(MGInventoryActivity.this
					.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	    
	    private TextWatcher watcher = new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
//						SetEnabledFalse();// Fasle
				String ofcase =et_case.getText().toString();
				String qty =et_qty.getText().toString();
				String cost =et_cost.getText().toString();
				
				 if (!ofcase.equals("") && !qty.equals("")) {
					et_total_qty.setText(String.valueOf(Integer.valueOf(ofcase)*Integer.valueOf(qty)));
					if (!cost.equals("")) {
						et_unit_cost.setText(MoleQUtil.fixPrintPrice(BigDecmialTool.div(Double.valueOf(cost), Integer.valueOf(qty))));
					}
				}
			}
		};
		
		private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

			@Override
			public void onClickYes() {
				// TODO Auto-generated method stub
				dispose();
				finish();
				
			}

			@Override
			public void onClickNo() {
//				mMessageDialog.dismiss();
			}

			@Override
			public void onClickOK() {
//				mMessageDialog.dismiss();
			}

		};

		@Override
		public void onCloseWithReturn(
				Class<? extends MoleQBaseDialog> pramClass, int viewId,
				String returnvalue) {
			// TODO Auto-generated method stub
			switch (viewId) {
			
			case R.id.et_date:
				
				int days = MoleQUtil.getBetweenDays(returnvalue,MoleQUtil.getNowwithFormat("yyyy-MM-dd"));
				if (Math.abs(days) > 100) {
					
					MessageBox.show(MGInventoryActivity.this, "Date cannot be more than 100 days");
					return;
				}
				et_date.setText(returnvalue);
				break;

			default:
				break;
			}
		}

		@Override
		public void onReturnValue(int what, Object obj) {
			// TODO Auto-generated method stub
			
		}

		
		public void onCloseWithReturn(Object obj) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onShowingMessageDlg(boolean isShowing) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onErrorEvent(String res) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onScannerEvent(String res) {
			// TODO Auto-generated method stub
			et_upc.setText(res);
			Keyboard();
			search();
			et_upc.setText("");
		}

		@Override
		public void onWeightEvent(int res) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTimeOutEvent() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onDataEvent(Object obj) {
			// TODO Auto-generated method stub
			
		}

		
		public void onEventResponse(Object obj) {
			// TODO Auto-generated method stub
			
		}
}
